package main

import (
	"net/http"
	"io/ioutil"
	"encoding/json"
	"fmt"
	"time"
	"strconv"
)

/* TO DO : each api coding json ? Abstract it */

func PushMsg(w http.ResponseWriter,req *http.Request){
	if req.Method != "POST"{
		http.Error(w,"Error Method",403)
	}
	bytes,err := ioutil.ReadAll(req.Body)
	if err != nil{
		http.Error(w,"Error request Body",403)
		return
	}
	var msg *Msg = &Msg{}
	fmt.Println("json string :",string(bytes))
	if err := json.Unmarshal(bytes,msg);err != nil{
		fmt.Println("json error :",err)
		http.Error(w,"Error json error",403)
		return
	}
	msg.Time = time.Now().Unix()
	db.PushMsg(msg)
	for _,toUser := range msg.To{
		channels,cerr :=GetChannelByUserid(toUser)
		if cerr != nil{
			http.Error(w,cerr.Error(),403)
			return
		}else{
			for _,channel := range channels{
				if channel != nil{
					channel.PushMsg(msg)
				}
			}
		}

	}
	n,werr := w.Write([]byte("success"))
	if werr != nil{
		fmt.Println("Write Http Error:",err,n)
		return
	}
	fmt.Println("API PushMsg() success ")

}
func PushMsgToRoom(w http.ResponseWriter,req *http.Request){
	if req.Method != "POST"{
		http.Error(w,"Error Method",403)
	}
	bytes,err := ioutil.ReadAll(req.Body)
	if err != nil{
		http.Error(w,"Error request Body",403)
		return
	}
	var msg *Msg = &Msg{}
	if err := json.Unmarshal(bytes,msg);err != nil{
		fmt.Println("json error :",err)
		http.Error(w,"Error json error",403)
		return
	}
	msg.Time = time.Now().Unix()
	db.PushMsg(msg)
	for _,roomid := range msg.To{
		cerr := PushToRoom(msg,roomid)
		if cerr != nil{
			http.Error(w,"Error: Roomid is not exist ",403)
			return
		}
	}
	n,werr := w.Write([]byte("success"))
	if werr != nil{
		fmt.Println("Write Http Error:",err,n)
		return
	}
	fmt.Println("API PushMsgToRoom() success ")
}

func GetMsgs(w http.ResponseWriter,req *http.Request){
	if req.Method != "GET"{
		http.Error(w,"Error Method",403)
	}

	req.ParseForm()
	mid,err := strconv.Atoi(req.Form.Get("mid"))
	if err != nil{
		http.Error(w,"mid not is number ",403)
	}
	userid := req.Form.Get("me")
	userKey := req.Form.Get("userKey")
	ty := req.Form.Get("type")
	var msgs []*Msg
	var merr error
	if len(ty)>0{
		msgs,merr = db.GetMsgsFromType(userKey,mid,ty)
	}else{
		msgs,merr = db.GetMsgs(userid,userKey,mid)
	}
	if merr != nil{
		http.Error(w,merr.Error(),403)
	}

	jsonMsgs,jerr := json.Marshal(msgs)
	if jerr != nil{
		http.Error(w,jerr.Error(),403)
	}
	n,werr := w.Write(jsonMsgs)
	if werr != nil{
		fmt.Println("Write Http Error:",werr,n)
		return
	}
	fmt.Println("API GetMsgs() success ",req.URL.String())
}


func GetOnlineUsers(w http.ResponseWriter,req *http.Request){
	if req.Method != "GET"{
		http.Error(w,"Error Method",403)
	}

	users :=  UserRouterI.GetOnlineUser()

	jsonUsers,jerr := json.Marshal(users)
	if jerr != nil{
		http.Error(w,jerr.Error(),403)
	}
	n,werr := w.Write(jsonUsers)
	if werr != nil{
		fmt.Println("Write Http Error:",werr,n)
		return
	}
	fmt.Println("API GetOnlineUsers() success ")
}


var db *MysqlDB
func InitHttpSever() {
	db = InitMysqlDB()
	addr := "192.168.1.105:3333"
	mux := http.NewServeMux()
	mux.HandleFunc("/getMsgs",GetMsgs)
	mux.HandleFunc("/push",PushMsg)
	mux.HandleFunc("/push/room",PushMsgToRoom)
	mux.HandleFunc("/online/user",GetOnlineUsers)
	fmt.Println("Listening ",addr)
	if err := http.ListenAndServe(addr,mux);err != nil{
		fmt.Println("Listening ",addr,"Error ",err)
	}
}
